<template>
  <div>
    <!-- 预览图片的对话框 平时隐藏 -->
    <el-dialog
      style="text-align: center"
      title="图片预览"
      :visible.sync="previewImageVisible"
      width="30%"
    >
      <img class="previewImage" :src="nowPreviewImage" alt="" />
    </el-dialog>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 提示区域 -->
      <el-alert
        title="添加商品页面"
        type="info"
        center
        show-icon
        v-bind:closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-row type="flex" justify="">
        <el-col :span="24">
          <el-steps
            :space="200"
            :active="activeIndex - 0"
            finish-status="success"
            align-center
          >
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step
            ><el-step title="完成"></el-step> </el-steps
        ></el-col>
      </el-row>
      <el-row type="flex" justify="" class="mt15">
        <el-col :span="24">
          <!-- 左侧tab栏区域 -->
          <el-form
            :model="addForm"
            :rules="addFormRules"
            ref="addFormRef"
            label-position="top"
            class="demo-ruleForm"
          >
            <el-tabs
              :tab-position="'left'"
              v-model="activeIndex"
              :before-leave="tabChange"
              @tab-click="tabClick"
            >
              <!-- 添加商品-- 基本信息 -->
              <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="addForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input
                    v-model="addForm.goods_price"
                    type="number"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                  <el-input
                    v-model="addForm.goods_weight"
                    type="number"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input
                    v-model="addForm.goods_number"
                    type="number"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品所属分类" prop="goods_cat">
                  <el-cascader
                    v-model="checkedCategoryKeys"
                    :options="categoryList"
                    :props="{
                      expandTrigger: 'hover',
                      value: 'cat_id',
                      label: 'cat_name',
                      children: 'children',
                    }"
                    @change="handleCategoryChange"
                  ></el-cascader>
                </el-form-item>
              </el-tab-pane>
              <!--添加商品-- 商品参数 -->
              <el-tab-pane label="商品参数" name="1">
                <!-- 渲染参数列表 -->
                <el-form-item
                  :key="item.attr_id"
                  v-for="item in attributes"
                  :label="item.attr_name"
                >
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox
                      border
                      :key="i"
                      v-for="(item2, i) in item.attr_vals"
                      :label="item2"
                    ></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-tab-pane>
              <!-- 添加商品-- 商品属性 -->
              <el-tab-pane label="商品属性" name="2">
                <el-form-item
                  :label="item.attr_name"
                  v-for="item in onlyAttributes"
                  :key="item.attr_id"
                >
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
              </el-tab-pane>
              <!-- 添加商品-- 商品图片 -->
              <el-tab-pane label="商品图片" name="3">
                <el-upload
                  :action="uploadUrl"
                  :on-preview="handleImagePreview"
                  :on-remove="handleImageRemove"
                  :on-success="handleImageRes"
                  list-type="picture"
                  :headers="uploadHeaders"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过1Mb
                  </div>
                </el-upload>
              </el-tab-pane>
              <!-- 添加商品-- 商品内容 -->
              <el-tab-pane label="商品内容" name="4">
                <!-- 富文本编辑器 -->
                <quill-editor
                  v-model="addForm.goods_introduce"
                  ref="myQuillEditorRef"
                >
                </quill-editor>
                <el-button type="primary" style="margin-top: 10px" @click="add"
                  >添加商品</el-button
                >
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //控制步骤条进行到哪一步 默认为0
      activeIndex: 0,
      //添加商品表单
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: "",
        pics: [], //存放商品图片
        goods_introduce: "", //介绍
        attrs: [], //商品的参数（数组），包含 `动态参数` 和 `静态属性`
      },
      //添加商品表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品所属分类", trigger: "blur" },
        ],
      },
      //商品分类列表
      categoryList: [],
      //级联选择器所保存的数组
      checkedCategoryKeys: [],
      //保存参数列表
      attributes: [],
      //保存only版参数列表
      onlyAttributes: [],
      //图片上传的地址
      uploadUrl: `http://127.0.0.1:8888/api/private/v1/upload`,
      //配置upload组件上传时候的请求头  发送token
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //保存正在预览的图片的绝对url地址
      nowPreviewImage: "",
      //预览图片对话框显示与否的变量  默认隐藏 false
      previewImageVisible: false,
    };
  },
  methods: {
    //获取商品分类列表的函数
    async getCategoryList() {
      const { data: res } = await this.$http.get(`categories`);
      if (res.meta.status == 200) {
        //获取成功了
        this.categoryList = res.data;
      } else {
        //获取失败
        this.$message.error("获取商品列表失败");
      }
    },
    //当级联选择的选择项发生变化时候触发
    handleCategoryChange(val) {
      if (val.length != 3) {
        this.checkedCategoryKeys = [];
        return;
      }
      var cat = val.join();
      this.addForm.goods_cat = cat;
    },
    //当tab栏切换时候需要触发的事件 用来阻止tab栏切换
    tabChange(activeName, oldActiveName) {
      if (oldActiveName == 0) {
        //如果原来的tab标签是 name=0 说明是基本信息页面切换过来的
        if (this.checkedCategoryKeys.length != 3) {
          this.$message.warning("请先选择商品分类");
          return false;
        }
      }
    },
    //当tab栏被点击的时候触发
    async tabClick() {
      if (this.activeIndex == 1) {
        //说明用户 选择了分类 来到了参数面板
        //发送请求获取商品参数
        const { data: res } = await this.$http.get(
          `categories/${this.checkedCategoryKeys[2]}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status == 200) {
          //获取参数列表成功
          res.data.forEach((element) => {
            element.attr_vals = element.attr_vals.split(",");
          });
          this.attributes = res.data;
          console.log(this.attributes);
        } else {
          this.$message.error("获取参数列表失败");
        }
      } else if (this.activeIndex == 2) {
        //说明用户来到商品属性页面，需要获取动态属性
        const { data: res } = await this.$http.get(
          `categories/${this.checkedCategoryKeys[2]}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        console.log(res);
        this.onlyAttributes = res.data;
      } else if (this.activeIndex == 3) {
        //来到了商品图片上传区域
        console.log("来到了商品图片上传区域");
      }
    },
    //图片预览触发的函数
    handleImagePreview(res) {
      //处理图片预览效果
      //先 保存图片的url绝对地址，再 弹出对话框，并 给对话框里的图片指定url
      console.log(res.response.data.url);
      this.nowPreviewImage = res.response.data.url;
      this.previewImageVisible = true;
    },
    //图片移除触发的函数
    handleImageRemove(res) {
      //用户移除图片之后，我们需要将add表单里的pics数组中对应的图片也给移除
      // console.log(res.response.data.tmp_path);
      this.addForm.pics.some((value, index) => {
        if (value.pic == res.response.data.tmp_path) {
          this.addForm.pics.splice(index, 1);
          return true;
        }
      });
      // console.log(this.addForm);
    },
    //图片上传成功后触发的函数，第一个参数就是返回结果
    handleImageRes(res) {
      //每次上传成功一个图片，就将地址保存到add表单里面的pics数组
      this.addForm.pics.push({ pic: res.data.tmp_path });
      // console.log(this.addForm);
    },
    //添加商品表单按钮提交
    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          //表单校验并没有通过
          return this.$message.error("请填写必填项");
        } else {
          //only 本来就是字符串了
          // console.log(this.onlyAttributes, this.attributes);
          //将动态参数和静态参数保存到addform表单的attrs属性中
          //处理addform表单的attrs数据
          this.onlyAttributes.forEach((item) => {
            let attrsItem = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            };
            this.addForm.attrs.push(attrsItem);
          });
          this.attributes.forEach((item) => {
            let attrsItem = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(" "),
            };
            this.addForm.attrs.push(attrsItem);
          });
          // console.log(this.addForm);
          //处理完表单数据，可以发送添加商品请求了
          const { data: res } = await this.$http.post(`goods`, this.addForm);
          console.log(res);
          if (res.meta.status == 201) {
            //添加商品成功了
            this.$message.success("添加成功");
            this.$router.push("/goods");
          } else {
            this.$message.error(res.meta.msg);
          }
        }
      });
    },
  },
  created() {
    //页面一创建就获取商品分类列表
    this.getCategoryList();
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 15px;
}
.mt15 {
  margin-top: 15px;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImage {
  width: 100%;
}
</style>